package com.sxj.PDMS.controller.admin;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sxj.PDMS.common.BaseResponse;
import com.sxj.PDMS.common.ErrorCode;
import com.sxj.PDMS.common.Result;
import com.sxj.PDMS.exception.BusinessException;
import com.sxj.PDMS.model.dto.admin.YusRecordConfirmRequest;
import com.sxj.PDMS.model.dto.student.YusRecordRequest;
import com.sxj.PDMS.model.entity.YusIncompleteRecord;
import com.sxj.PDMS.model.entity.YusRecordSheet;
import com.sxj.PDMS.model.vo.PagingQueryResponse;
import com.sxj.PDMS.service.YusIncompleteRecordService;
import com.sxj.PDMS.service.YusRecordSheetService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/admin")
@Slf4j
public class AdminYusRecordController {
    @Autowired
    private YusRecordSheetService yusRecordSheetService;
    @Autowired
    private YusIncompleteRecordService yusIncompleteRecordService;

    @GetMapping("/selectAll_yusRecord")
    public BaseResponse<PagingQueryResponse<YusRecordSheet>> selectYusRecord(@RequestParam(defaultValue = "1") Integer page,
                                                                             @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("分页查询 ：page:{}, pageSize:{}", page, pageSize);
        PagingQueryResponse<YusRecordSheet> pagingQueryResponse = yusRecordSheetService.selectAll(page, pageSize);
        return Result.success(pagingQueryResponse);

    }

    @GetMapping("/select_yusRecord")
    public BaseResponse<PagingQueryResponse<YusRecordSheet>> selectYusRecordSheetWithCondition(@RequestParam(defaultValue = "1") Integer page,
                                                                                               @RequestParam(defaultValue = "10") Integer pageSize,
                                                                                               YusRecordRequest yusRecordRequest) {

        PagingQueryResponse<YusRecordSheet> pagingQueryResponse = yusRecordSheetService.yusRecordSheetSelect(page, pageSize, yusRecordRequest);

        return Result.success(pagingQueryResponse);
    }

    @GetMapping("/select_yusRecordById/{id}")
    public BaseResponse<YusRecordSheet> selectYusRecordSheetById(@PathVariable Long id) {
        log.info("查询id为：{}的青年大学习记录", id);

        YusRecordSheet yusRecordSheet = yusRecordSheetService.getById(id);
        if (yusRecordSheet == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "库中无该编号");
        }
        return Result.success(yusRecordSheet);
    }


    @Transactional
    @PutMapping("/confirm_yusRecord")
    public BaseResponse<Boolean> confirmYusRecord(@RequestBody YusRecordConfirmRequest yusRecordConfirmRequest) {
        log.info("确认青年大学习记录：{}", yusRecordConfirmRequest);

        System.out.println("id:" + yusRecordConfirmRequest.getId());
        YusRecordSheet oldYusRecordSheet = yusRecordSheetService.getById(yusRecordConfirmRequest.getId());

        if (oldYusRecordSheet == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "库中无该编号");
        }
        String studentNumber = oldYusRecordSheet.getStudentNumber();
        QueryWrapper<YusIncompleteRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_number", studentNumber);
        YusIncompleteRecord yusIncompleteRecord = yusIncompleteRecordService.getOne(queryWrapper);
        boolean b = yusIncompleteRecordService.removeById(yusIncompleteRecord.getId());
        if (!b) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除失败");
        }
        // 更新状态
        oldYusRecordSheet.setIsConfirm(1);

        boolean updated = yusRecordSheetService.updateById(oldYusRecordSheet);

        if (!updated) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "确认失败");
        }
        return Result.success();
    }

    @GetMapping("/selectAll_yusIncompleteRecord")
    public BaseResponse<PagingQueryResponse<YusIncompleteRecord>> selectYusIncompleteRecord(@RequestParam(defaultValue = "1") Integer page,
                                                                                            @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("分页查询 ：page:{}, pageSize:{}", page, pageSize);
        PagingQueryResponse<YusIncompleteRecord> pagingQueryResponse = yusIncompleteRecordService.selectAll(page, pageSize);
        return Result.success(pagingQueryResponse);

    }

    @GetMapping("/select_yusIncompleteRecord")
    public BaseResponse<PagingQueryResponse<YusIncompleteRecord>> selectYusIncompleteRecordWithCondition(@RequestParam(defaultValue = "1") Integer page,
                                                                                                         @RequestParam(defaultValue = "10") Integer pageSize,
                                                                                                         YusRecordRequest yusRecordRequest) {

        PagingQueryResponse<YusIncompleteRecord> pagingQueryResponse = yusIncompleteRecordService.yusIncompleteRecordSelect(page, pageSize, yusRecordRequest);

        return Result.success(pagingQueryResponse);
    }

    /**
     * 根据条件查询并下载未完成青年大学习的学生信息
     *
     * @param yusRecordRequest
     * @return response
     */
    // todo 前后端联调 swagger无法测试
    @ApiOperation(value = "selectAndDownloadYusIncompleteRecord", produces = "application/octet-stream")
    @GetMapping("/selectAndDownload_yusIncompleteRecord")
    public void selectAndDownloadYusIncompleteRecord(YusRecordRequest yusRecordRequest,
                                                     HttpServletResponse response) {
        log.info("根据条件查询并下载学生信息 ：yusRecordRequest:{}", yusRecordRequest);

        try {
            // 设置响应内容类型
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            // 设置响应头，告诉浏览器这是一个附件，应该下载而不是直接打开
            String fileName = "未完成学生信息表.xlsx"; // 你可以根据需要自定义文件名
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

            // 调用服务层方法，并传递响应对象
            yusIncompleteRecordService.selectAllStudentAndDownload(yusRecordRequest, response);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载未完成学生信息失败");
        }
    }

    @GetMapping("file/{imageUrl}")
    public static void downLoad(@PathVariable String imageUrl, HttpServletResponse response) {
        log.info("下载图片：imageUrl:{}", imageUrl);

        //todo：/学生提交青年大学习的存放路径
        String path = "D:\\user\\Desktop\\store\\YUS\\";
        OutputStream outPutStream;
        List<String> fileNames = FileUtil.listFileNames(path);
        String avatar = fileNames.stream().filter(name -> name.contains(imageUrl)).findAny().orElse("");
        try {
            if (StrUtil.isNotEmpty(avatar)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(avatar, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(path + "\\" + avatar);
                outPutStream = response.getOutputStream();
                outPutStream.write(bytes);
                outPutStream.flush();
                outPutStream.close();

                log.info("下载成功");
            } else {
                log.info("下载失败");
            }
        } catch (Exception e) {
            System.out.println(avatar + "下载失败");
        }
    }
}
